// cFinalPage.cpp : implementation file
//

#include "stdafx.h"
#include "QPMig.h"
#include "cFinalPage.h"
#include "cNotesFolderInfo.h"
#include "cQuickPlaceDB.h"


#include "noteshelperfunctions.h"
#include "helper.h"

extern CQPMigApp theApp;


#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

/////////////////////////////////////////////////////////////////////////////
// cFinalPage property page

IMPLEMENT_DYNCREATE(cFinalPage, CPropertyPageEx)

cFinalPage::cFinalPage() : CPropertyPageEx(cFinalPage::IDD,0,IDS_QPLOGHEADERTITLE,IDS_QPLOGHEADERSUBTITLE)
{
	//{{AFX_DATA_INIT(cFinalPage)
	m_strResult = _T("");
	//}}AFX_DATA_INIT
}

cFinalPage::~cFinalPage()
{
}

void cFinalPage::DoDataExchange(CDataExchange* pDX)
{
	CPropertyPageEx::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(cFinalPage)
	DDX_Text(pDX, IDC_EDIT1, m_strResult);
	//}}AFX_DATA_MAP
}


BEGIN_MESSAGE_MAP(cFinalPage, CPropertyPageEx)
	//{{AFX_MSG_MAP(cFinalPage)
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// cFinalPage message handlers

BOOL cFinalPage::OnSetActive() 
{
	CString cStatus;
	//CString cVersion=GetVersionInfo(AfxGetResourceHandle(),"ProductVersion");
	//cStatus.Format("The exporter version is %s",cVersion); 
	//theApp.stControl.pLog->LogOneLine(cStatus);
	//theApp.stControl.pDebugLog->LogOneLine(cStatus);
	//theApp.stControl.pDebugLog->Flush();
	COleDateTime codt=COleDateTime::GetCurrentTime();
	cStatus.Format("The export starts at %s",codt.Format()); 
	theApp.stControl.pLog->LogOneLine(cStatus);
	theApp.stControl.pDebugLog->LogOneLine(cStatus);
	theApp.stControl.pDebugLog->Flush();

	CPropertySheet* psheet = (CPropertySheet*) GetParent();   
	psheet->SetWizardButtons(PSWIZB_FINISH);
	CFileStatus status;
	CWaitCursor cw;
	MSXML2::IXMLDOMDocument2Ptr pXMLDoc=NULL;
	MSXML2::IXMLDOMElementPtr pNode=NULL;
	CString cf;
	CString cfname;
	


	HRESULT hr=pXMLDoc.CreateInstance(__uuidof(DOMDocument40));
	if(SUCCEEDED(hr))
	{
		pXMLDoc->setProperty("SelectionLanguage", "XPath");

		MSXML2::IXMLDOMProcessingInstructionPtr pPI = pXMLDoc->createProcessingInstruction("xml", "version='1.0' encoding='UTF-8'");

		_variant_t vNullVal;
		vNullVal.vt = VT_NULL;
		pXMLDoc->insertBefore(pPI, vNullVal);
		pPI.Release();
		MSXML2::IXMLDOMElementPtr pRootContainerElem=NULL;
		MSXML2::IXMLDOMElementPtr pRootElem=pXMLDoc->createElement(L"Import");
		MSXML2::IXMLDOMElementPtr pSettingsContainerElem=NULL;


		//Fix displaynames

		if(pRootElem)
		{
			pXMLDoc->documentElement=pRootElem;
			pSettingsContainerElem=pXMLDoc->createElement(L"settings");
			pNode=pXMLDoc->createElement(L"locale");
			CString cLCID="1033";
			cLCID.Format("%d",theApp.stControl.m_nLocale);
			BSTR bstr=cLCID.AllocSysString();

			pNode->put_text(bstr);
			::SysFreeString(bstr);
			pSettingsContainerElem->appendChild(pNode);
			pNode.Release();
			pRootElem->appendChild(pSettingsContainerElem);
			pSettingsContainerElem.Release();

			pRootContainerElem=pXMLDoc->createElement(L"rootcontainer");
			pNode=pXMLDoc->createElement(L"type");
			if(theApp.stControl.m_strContainerType=="Area")
				pNode->put_text(L"Area");
			else
				pNode->put_text(L"Site");
			pRootContainerElem->appendChild(pNode);
			pNode.Release();

			pNode=pXMLDoc->createElement(L"name");
			pNode->put_text(theApp.stControl.bstrSiteContainerRoot);
			pRootContainerElem->appendChild(pNode);
			pNode.Release();
			pRootElem->appendChild(pRootContainerElem);


			cfname.Format("%s%s",theApp.stControl.m_strDirectoryPath,"result.txt");
			theApp.stControl.pDebugLog->LogOneLine("Enumerating through the databases");
			for(int i=0;i<=theApp.stControl.m_objQuickPlaces.GetUpperBound();i++)
			{
				cQuickPlaceDB *pdb=(cQuickPlaceDB *)theApp.stControl.m_objQuickPlaces.GetAt(i);
				if(pdb)
				{
					pdb->cArUnids.RemoveAll();
					theApp.stControl.m_strCurDir=theApp.stControl.m_strDirectoryPath+theApp.stControl.m_strQPName;
					theApp.stControl.pdb=pdb;
					theApp.stControl.m_strQPName=pdb->strName;
					theApp.stControl.pDebugLog->LogOneLine(pdb->strName);
					theApp.stControl.pDebugLog->Flush();
					try
					{
						ProcessDB(pdb,pXMLDoc,pRootContainerElem,pRootElem,cfname);
					}
					catch(CException* e)
					{
						theApp.stControl.pDebugLog->LogOneLine("Exception when processing the database");
						theApp.stControl.pDebugLog->LogOneLine(pdb->strName);
						theApp.stControl.pDebugLog->Flush();
						char szError[255];

						if(e->GetErrorMessage(szError,255))
							theApp.stControl.pDebugLog->LogOneLine(szError);
						theApp.stControl.pDebugLog->Flush();
						e->ReportError();
						e->Delete();


					}

				}
			}



		}
		codt=COleDateTime::GetCurrentTime();
		cf.Format("%s\\%s",theApp.stControl.m_strDirectoryPath,"struct.xml");
		cStatus.Format("The export ended at %s after exporting %d documents and %d list items\r\nThe exported manifest was: \"%s\"",codt.Format(),theApp.stControl.NrOfDocs,theApp.stControl.NrOfListItems,cf); 
		theApp.stControl.pLog->LogOneLine(cStatus);

		theApp.stControl.pLog->Close();

		BSTR bstr=cf.AllocSysString();
		pXMLDoc->save(bstr);
		::SysFreeString(bstr);
		pRootContainerElem.Release();
		pXMLDoc.Release();
	}


	//FILE *fpResult=fopen("c:\\result.txt","rb");
	if( CFile::GetStatus( cfname, status ) )   // static function
	{
#ifdef _DEBUG
		afxDump << "Full file name = " << status.m_szFullName << " size ="<< status.m_size << "\n";
#endif
	}
	char *pstr=(char *)malloc(status.m_size+1);   
	CFile cfile(cfname,CFile::modeRead);
	UINT uintread=cfile.Read(pstr,status.m_size);
	pstr[uintread]='\0';
	m_strResult =pstr;
	free(pstr);	
	cfile.Close();

	UpdateData(FALSE);

	return CPropertyPageEx::OnSetActive();
}



BOOL cFinalPage::OnWizardFinish() 
{


	return CPropertyPageEx::OnWizardFinish();
}


//// This retrieves the version info from the executable
//CString cFinalPage::GetVersionInfo(HMODULE hLib, CString csEntry)
//	{
//	CString csRet;
//
//	HRSRC hVersion = ::FindResource( AfxGetResourceHandle(), 
//    MAKEINTRESOURCE(VS_VERSION_INFO), RT_VERSION );
//  if (hVersion != NULL)
//  {
//	HGLOBAL hGlobal = ::LoadResource( AfxGetResourceHandle(), hVersion ); 
//    if ( hGlobal != NULL)  
//    {  
//  
//      LPVOID versionInfo  = LockResource(hGlobal);  
//      if (versionInfo != NULL)
//      {
//        DWORD vLen,langD;
//        BOOL retVal;    
//    
//        LPVOID retbuf=NULL;
//    
//        static char fileEntry[256];
//
//        wsprintf(fileEntry,"\\VarFileInfo\\Translation");
//				retVal = VerQueryValue(versionInfo,fileEntry,&retbuf,(UINT *)&vLen);
//        if (retVal && vLen==4) 
//        {
//          memcpy(&langD,retbuf,4);            
//          wsprintf(fileEntry, "\\StringFileInfo\\%02X%02X%02X%02X\\%s",
//                  (langD & 0xff00)>>8,langD & 0xff,(langD & 0xff000000)>>24, 
//                  (langD & 0xff0000)>>16, csEntry);            
//        }
//        else 
//          wsprintf(fileEntry, "\\StringFileInfo\\%04X04B0\\%s", 
//            GetUserDefaultLangID(), csEntry);
//
//        if (VerQueryValue(versionInfo,fileEntry,&retbuf,(UINT *)&vLen)) 
//          csRet = (char*)retbuf;
//      }
//    }
//
//    UnlockResource( hGlobal );  
//    FreeResource( hGlobal );  
//  }
//
//  return csRet;
//	}
